package com.demo.search.spring;

import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;

import com.demo.search.util.LuceneUtils;

/**
 * IndexWriter的工厂类
 * @author ryuu.kk
 *
 */
public class IndexWriterFactoryBean implements FactoryBean<IndexWriter>, InitializingBean {

	/**
	 * 索引文件路径
	 */
	private String indexPath;
	
	/**
	 * 索引写入对象配置属性
	 */
	private IndexWriterConfig writerConfig;
	
	/**
	 * 索引写入对象
	 */
	private IndexWriter indexWriter;
	
	/**
	 * 取得真实路径
	 * @param path
	 * @return String
	 */
	protected String getRealPath(String path) {
		return path;
	}
	
	@Override
	public IndexWriter getObject() throws Exception {
		if (indexWriter == null) {
			System.err.println("not found IndexWriter, create it in path:[" + getRealPath(indexPath) + "]");
			Directory directory = LuceneUtils.createFSDriectory(getRealPath(indexPath));
			indexWriter = new IndexWriter(directory, writerConfig);
		}
		return indexWriter;
	}

	@Override
	public Class<?> getObjectType() {
		return indexWriter == null ? org.apache.lucene.index.IndexWriter.class : indexWriter.getClass();
	}

	@Override
	public boolean isSingleton() {
		return true;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		Assert.notNull(writerConfig);
	}
	
	public void setIndexPath(String indexPath) {
		this.indexPath = indexPath;
	}

	public void setWriterConfig(IndexWriterConfig writerConfig) {
		this.writerConfig = writerConfig;
	}

}
